﻿using System.Linq;
using Model.Repositories;

namespace Presenter.Groups
{
    public class GroupHomePresenter
    {
        private IGroupHomeView _view;

        public GroupHomePresenter(IGroupHomeView view, int id, string email, string password)
        {
            _view = view;

            _view.UserJoined += _view_UserJoined;
            _view.UserLeft   += _view_UserLeft;

            var obj = RepositoryManager.Instance.GroupRepository.Get(id);

            _view.ShowGroup(id, obj.Type, obj.Title);

            var user = RepositoryManager.Instance.UserRepository.GetByEmailAndPassword(email, password);
            if (user != null && (user.Groups.FirstOrDefault(o => o.Id == id) != null || (user.OwnedGroups.FirstOrDefault(o => o.Id == id)) != null))
                _view.IsJoined = true;
            else
                _view.IsJoined = false;
        }

        void _view_UserLeft(string email, string password, int id)
        {
            var user  = RepositoryManager.Instance.UserRepository.GetByEmailAndPassword(email, password);
            var group = RepositoryManager.Instance.GroupRepository.Get(id);
            if (group != null && user != null && user.Groups.FirstOrDefault(o => o.Id == group.Id) != null)
            {
                user.Groups.Remove(user.Groups.FirstOrDefault(o => o.Id == group.Id));
                RepositoryManager.Instance.UserRepository.Update(user);
            }
        }

        void _view_UserJoined(string email, string password, int id)
        {
            var user  = RepositoryManager.Instance.UserRepository.GetByEmailAndPassword(email, password);
            var group = RepositoryManager.Instance.GroupRepository.Get(id);
            if (group != null && user != null && user.Groups.FirstOrDefault(o => o.Id == group.Id) == null)
            {
                user.Groups.Add(group);
                RepositoryManager.Instance.UserRepository.Update(user);
            }
        }

        public void Reload(IGroupHomeView view, int id, string email, string password)
        {
            _view = view;

            _view.UserJoined += _view_UserJoined;
            _view.UserLeft   += _view_UserLeft;

            var obj = RepositoryManager.Instance.GroupRepository.Get(id);

            _view.ShowGroup(id, obj.Type, obj.Title);

            var user = RepositoryManager.Instance.UserRepository.GetByEmailAndPassword(email, password);
            if (user != null && (user.Groups.FirstOrDefault(o => o.Id == id) != null || (user.OwnedGroups.FirstOrDefault(o => o.Id == id)) != null))
                _view.IsJoined = true;
            else
                _view.IsJoined = false;
        }
    }
}
